# ai_sop_system/cms_system.py
from datetime import datetime
from typing import Dict, List, Any
from enum import Enum


class ContentType(Enum):
    SOP = "standard_operating_procedure"
    TRAINING = "training_material"
    REFERENCE = "reference_document"
    TEMPLATE = "template"
    GUIDELINE = "guideline"


class CMSSystem:
    """内容管理系统"""

    def __init__(self):
        self.content_repository = {}
        self.content_categories = {}
        self.tag_system = TagSystem()

    def process_data(self, imported_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理导入的数据"""
        print("📚 CMS系统处理数据中...")

        # 内容分类
        content_categories = self._categorize_content(imported_data)

        # 标签生成
        auto_tags = self.tag_system.generate_tags(imported_data)

        # 内容关联
        related_content = self._find_related_content(imported_data)

        # 创建内容记录
        content_record = self._create_content_record(imported_data, content_categories, auto_tags)

        result = {
            "content_id": content_record["content_id"],
            "categories": content_categories,
            "tags": auto_tags,
            "related_content": related_content,
            "processing_time": datetime.now().isoformat(),
            "content_metadata": content_record
        }

        print("✅ CMS数据处理完成")
        return result

    def _categorize_content(self, data: Dict) -> List[str]:
        """内容分类"""
        categories = []

        # 基于用户行为分类
        behavior_data = data.get("standardized_data", {}).get("behavior_patterns", {})
        if behavior_data.get("usage_frequency", {}).get("daily_logins", 0) > 5:
            categories.append("high_frequency_user")

        # 基于偏好分类
        preference_data = data.get("standardized_data", {}).get("preference_summary", {})
        if preference_data.get("prefers_visual", False):
            categories.append("visual_learner")

        # 基于上下文分类
        context_data = data.get("standardized_data", {}).get("context_summary", {})
        if context_data.get("environment") == "office":
            categories.append("professional_context")

        return categories

    def _find_related_content(self, data: Dict) -> List[Dict]:
        """查找相关内容"""
        related = []

        # 基于用户偏好推荐内容
        preferences = data.get("standardized_data", {}).get("preference_summary", {})
        if preferences.get("preferred_categories"):
            for category in preferences["preferred_categories"]:
                related.append({
                    "type": "recommended",
                    "category": category,
                    "reason": "用户偏好匹配"
                })

        # 基于行为模式推荐
        behavior = data.get("standardized_data", {}).get("behavior_patterns", {})
        if behavior.get("common_actions"):
            for action in behavior["common_actions"]:
                related.append({
                    "type": "behavior_based",
                    "action": action,
                    "reason": "常用操作相关"
                })

        return related

    def _create_content_record(self, data: Dict, categories: List[str], tags: List[str]) -> Dict:
        """创建内容记录"""
        content_id = f"CONTENT_{datetime.now().strftime('%Y%m%d_%H%M%S')}"

        content_record = {
            "content_id": content_id,
            "creation_time": datetime.now(),
            "data_source": "ai_assistant_collection",
            "categories": categories,
            "tags": tags,
            "user_profile_summary": data.get("standardized_data", {}).get("user_profile", {}),
            "derived_features": data.get("derived_features", {}),
            "predictive_metrics": data.get("predictive_metrics", {}),
            "content_type": ContentType.SOP.value,
            "version": "1.0",
            "status": "active"
        }

        # 存储到内容库
        self.content_repository[content_id] = content_record

        return content_record


class TagSystem:
    """标签系统"""

    def generate_tags(self, data: Dict) -> List[str]:
        """生成标签"""
        tags = []

        # 基于用户特征生成标签
        user_profile = data.get("standardized_data", {}).get("user_profile", {})
        if user_profile.get("experience_level"):
            tags.append(f"exp_{user_profile['experience_level']}")

        # 基于行为生成标签
        behavior = data.get("standardized_data", {}).get("behavior_patterns", {})
        if behavior.get("engagement_level"):
            tags.append(f"engagement_{behavior['engagement_level']}")

        # 基于偏好生成标签
        preferences = data.get("standardized_data", {}).get("preference_summary", {})
        if preferences.get("prefers_visual"):
            tags.append("visual_learner")
        if preferences.get("prefers_hands_on"):
            tags.append("hands_on_learner")

        # 基于预测指标生成标签
        predictions = data.get("predictive_metrics", {})
        if predictions.get("sop_success_probability", 0) > 0.8:
            tags.append("high_success_probability")

        return tags